from django.contrib.auth.decorators import login_required
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from .models import items
from .models import stock
from home.context_processors import hasGroup
from django.contrib import messages
from django.shortcuts import render, HttpResponse, redirect
import time
import datetime
from profiles.models import Department



@login_required
def add_med(request):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        c = {}
        c['manufacture']=Department.objects.all()
        c.update(csrf(request))
        return render(request, 'stocks/add_medecine.html', c)
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')

@login_required
def add_new_medicine(request):
    print("add_medcine")
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        item_name = request.POST.get('medicine_name', '')
        cost_price = request.POST.get('cost_price', '')
        sell_price = request.POST.get('sell_price','')
        manufacturer = Department.objects.get(pk=int(request.POST.get('manufacturer', '')))
        description = request.POST.get('description', '')
        print(item_name)

        Items = items(item_name=item_name,cost_price=cost_price,sell_price=sell_price,manufacturer=manufacturer,description=description)
        Items.save()
        messages.add_message(request, messages.INFO, 'New Medicine Successfully Added')
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')

    return HttpResponseRedirect('/stock/view_medicine')

@login_required
def view_medicine(request):
    c = {}
    c.update(csrf(request))

    if hasGroup(request.user, 'inventory_manager'):
        target_item=request.POST.get('target_item','')
        if target_item=='':
            c['selectItem']= True
            c['post_list']= items.objects.all()
            return render(request, 'stocks/view_medicine.html',c)
        else:
            post_list_new = items.objects.filter(item_name__contains=target_item)
            print(post_list_new)
            c['post_list']=post_list_new
            return render(request, 'stocks/view_medicine.html', c)
    return HttpResponseRedirect('/home')

@login_required
def change_medicine(request, id):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        c = {'items': items.objects.get(pk=id)}
        c.update(csrf(request))
        return render(request, 'stocks/change_medicine.html', c)
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')

@login_required
def do_change_medicine(request):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        target_item =items.objects.get(pk=int(request.POST.get('id')))
        Item_name=request.POST.get('item_name', '')
        Cost_price=request.POST.get('cost_price', '')
        Sell_price=request.POST.get('sell_price', '')
        Manufacture = Department.objects.get(pk=int(request.POST.get('manufacturer', '')))
        Description=request.POST.get('description','')
        if Item_name=='':
            target_item.item_name=target_item.item_name
        else:
            target_item.quantity=Item_name
        if Cost_price=='':
            target_item.cost_price = target_item.cost_price
        else:
            target_item.cost_price=Cost_price

        if Sell_price=='':
            target_item.sell_price = target_item.sell_price
        else:
            target_item.sell_price=Sell_price
        if Manufacture=='':
            target_item.manufacturer=target_item.manufacturer
        else:
            target_item.manufacturer=Manufacture
        if Description=='':
            target_item.description=target_item.description
        else:
            target_item.description=Description
        target_item.save()

    messages.add_message(request, messages.INFO, 'medicine Successfully Changed')
    return HttpResponseRedirect('/stock/')

def delete_medicine(request, id):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        items.objects.get(id=id).delete()
        messages.add_message(request, messages.INFO, 'medicine Successfully Deleted')
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/stock/')

@login_required
def view_stock(request):
    c = {}
    c.update(csrf(request))
    if hasGroup(request.user, 'inventory_manager'):
        target_item=request.POST.get('target_item','')
        if target_item == '':
            c['item'] = items.objects.all()
            return render(request, 'stocks/view_stock.html', c)
        else:
            post_list_new = items.objects.filter(item_name__contains=target_item)
            c['item'] = post_list_new
            return render(request, 'stocks/view_stock.html', c)

    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
        return HttpResponseRedirect('/home')


@login_required
def do_view_stock(request):
    item_selected = request.POST.get('item_selected', '')
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        c = {}
        c.update(csrf(request))
        c['isInventory_manager'] = True
        c['stock'] = stock.objects.filter(item=item_selected)
        stocks = c['stock']
        c['goodstock'] = []
        c['badstock'] = []
        nowTime_str = datetime.datetime.now().strftime('%Y-%m-%d')
        e_time = time.mktime(time.strptime(nowTime_str, "%Y-%m-%d"))
        for s in stocks:
            if time.mktime(time.strptime(s.expiry_date.strftime('%Y-%m-%d'), "%Y-%m-%d")) < e_time:
                c['badstock'].append(s)
            else:
                c['goodstock'].append(s)
        return render(request, 'stocks/do_view_stock.html', c)



@login_required
def add_stock(request):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        c = {}
        c.update(csrf(request))
        c['item'] = items.objects.all()
        c['stock']= stock.objects.all()
        target_item=request.POST.get('target_item','')
        if target_item=='':
            c['selectItem']= True
            c['post_list']= items.objects.all()
            return render(request, 'stocks/add_stock.html',c)
        else:
            post_list_new = items.objects.filter(item_name__contains=target_item)
            print(post_list_new)
            c['post_list']=post_list_new
            return render(request, 'stocks/add_stock.html', c)

    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')


@login_required
def do_add_stock(request):
    print("add_new_stock")
    user = request.user
    if hasGroup(user, 'inventory_manager'):

        items = request.POST.get('item', '')
        quantity=request.POST.get('quantity', '')
        purchase_date = request.POST.get('purchase_date', '')
        expiry_date = request.POST.get('expiry_date', '')

        new_stock = stock(item_id=items, purchase_date=purchase_date, quantity=quantity,expiry_date=expiry_date)
        new_stock.save()
        messages.add_message(request, messages.INFO, 'New stock Successfully Added')
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')

    return HttpResponseRedirect('/home')

#change
@login_required
def change_stock(request, id):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        c = {'stock': stock.objects.get(pk=id)}
        c.update(csrf(request))
        return render(request, 'stocks/change_stock.html', c)
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')

@login_required
def do_change_stock(request):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        target_stock = stock.objects.get(pk=int(request.POST.get('id')))
        Quantity=request.POST.get('quantity', '')
        Purchase_date=request.POST.get('purchase_date', '')
        Expiry_date=request.POST.get('expiry_date', '')
        if Quantity=='':
            target_stock.quantity=target_stock.quantity
        else:
            target_stock.quantity=Quantity
        if Purchase_date=='':
            target_stock.purchase_date = target_stock.purchase_date
        else:
            target_stock.purchase_date=Purchase_date

        if Expiry_date=='':
            target_stock.expiry_date = target_stock.expiry_date
        else:
            target_stock.expiry_date=Expiry_date


        target_stock.save()

    messages.add_message(request, messages.INFO, 'stock Successfully Changed')
    return HttpResponseRedirect('/stock/')

#DELETE
def delete_stock(request, id):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        stock.objects.get(id=id).delete()
        messages.add_message(request, messages.INFO, 'stock Successfully Deleted')
    else:
        messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/stock/')

def quick_delete(request):
    user = request.user
    if hasGroup(user, 'inventory_manager'):
        ids = request.POST.getlist("ids",[])
        if type(ids) == type([]):
            for id in ids:
                stock.objects.get(id=id).delete()
        else:
            stock.objects.get(id=ids).delete()
        messages.add_message(request, messages.INFO, 'stock delete Successfully.')
        return HttpResponseRedirect('/stock/')
    messages.add_message(request, messages.WARNING, 'Access Denied.')
    return HttpResponseRedirect('/home')







